package com.jieyun.core.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * 数据源配置
 * 
 * @author trek
 *
 */
@Configuration
public class DatasourceConfig {
	
	/**
	 * 配置数据源
	 * @return
	 */
	@Bean
	@ConfigurationProperties("spring.datasource")
	public DataSource druid() {
		return new DruidDataSource();
	}

	/**
	 * 配置Druid的Servlet
	 */
	@Bean
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean servletBean = new ServletRegistrationBean(
				new com.alibaba.druid.support.http.StatViewServlet(), "/druid/*");
		// 配置相关的属性
		Map<String, String> initParameters = new HashMap<>();
		// 放置各种的属性
		initParameters.put("loginUsername", "admin");
		initParameters.put("loginPassword", "123456");
		servletBean.setInitParameters(initParameters);
		return servletBean;
	}

	/**
	 * 配置Druid的filter信息
	 * 
	 * @return
	 */
	@Bean
	public FilterRegistrationBean druidFilter() {
		FilterRegistrationBean filterBean = new FilterRegistrationBean();
		filterBean.setFilter(new WebStatFilter());
		// 配置拦截所有的请求
		filterBean.setUrlPatterns(Arrays.asList("/*"));
		Map<String, String> initParameters = new HashMap<>();
		// 排除所有不需要拦截的请求
		initParameters.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
		filterBean.setInitParameters(initParameters);
		return filterBean;
	}
}
